package cn.com.dmg.myspringboot.file.pdf;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

/**
 * @description: pdf 转图片工具类
 * @author: libai
 * @create: 2024-04-03 10:30
 */
public class PdfToImagesUtil {
    public static void main(String[] args) {
        // PDF文件路径
        String pdfFilePath = "D:\\opt\\shth\\alcertificatemode\\hj2.pdf";
        // 输出图片的路径前缀
        String outputPrefix = "D:\\opt\\shth\\alcertificatemode\\pdftopng\\";
        // 图片格式
        String imageFormat = "png";
        // 图片分辨率（DPI）
        int dpi = 300;

        List<String> list = pdfToImage(pdfFilePath, outputPrefix, imageFormat, dpi);
    }


    public static List<String> pdfToImage(String pdfFilePath, String outputPrefix, String imageFormat, int dpi) {
        List<String> list=new ArrayList<>();
        try (PDDocument document = PDDocument.load(new File(pdfFilePath))) {
            PDFRenderer pdfRenderer = new PDFRenderer(document);
            for (int page = 0; page < document.getNumberOfPages(); ++page) {
                BufferedImage bim = pdfRenderer.renderImageWithDPI(page, dpi);
                // 生成图片文件名
                String imageFileName = String.format("%s%d.%s", outputPrefix, page + 1, imageFormat);
                // 将图片写入文件
                File file = new File(imageFileName);
                File parentFile = file.getParentFile();
                if (!parentFile.exists()){
                    parentFile.mkdirs();
                }
                ImageIO.write(bim, imageFormat, file);
                System.out.println("Page " + (page + 1) + " saved as " + imageFileName);
                list.add(imageFileName);
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
